<?php
declare (strict_types=1);

namespace app\common\queue\upload;

use app\common\library\Queue;
use app\common\model\Attach;
use eduline\upload\Client as FileClient;
use think\facade\Request;

/**
 * 附件同步到云端
 */
class Sync
{
    public function run()
    {
        // 需要上传的附件id
        $attachId = Request::post('attach_id');

        // 限制同时上传的进程数量 防止服务器出现负荷
        $uploading = Attach::where('status', 3)->findOrEmpty();
        if (!$uploading->isEmpty()) {
            // 任务是否超时
            $exptime = $uploading->getAttr('upload_time') + 3600 * 4;
            if ($exptime >= time()) {
                // 重发任务，延迟1分钟执行
                Queue::push('UploadYunSync', ['attach_id' => $attachId], 60);

                return;
            } else {
                // 正在上传的任务出现异常了, 更改状态等待重新上传
                Attach::update(['status' => 2], ['id' => $uploading->id]);
            }
        }

        // 查询附件
        $attach = app(Attach::class)->where('id', $attachId)->where('status', 2)->findOrEmpty();
        if (!$attach->isEmpty()) {
            // 是否证书类文件
            if (!in_array($attach->getAttr('extension'), ['crt', 'pem'])) {
                // 获取附件上传的机构
                $filedata = $attach->getAttr('filedata');
                $isTemp   = is_array($filedata) ? (bool)($filedata['is_temp'] ?? false) : false;
                if (!$isTemp) {
                    Attach::update(['upload_time' => time()], ['id' => $attachId]);
                    // 这里强制更改请求的机构id，用于获取对应附件上传的机构配置
                    $mhmId            = is_array($filedata) ? ($filedata['mhm_id'] ?? 1) : 1;
                    request()->mhm_id = $mhmId ?: 1;
                    $client           = new FileClient($attach['to_stock']);
                    $client->putYunFile($attach);
                } else {
                    // 修改状态为正常
                    Attach::update(['status' => 1], ['id' => $attachId]);
                }
            } else {
                // 修改状态为正常
                Attach::update(['status' => 1], ['id' => $attachId]);
            }
        }
    }
}
